package com.imooc.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * Hystrix
 * @author steve
 * @date 2020/6/29 11:31
 */
@RestController
@RequestMapping
@DefaultProperties(defaultFallback = "defaultFallback")//默认回退函数，实现服务降级逻辑的方法
public class HystrixController {

    //超时设置
//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
//    })
//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), //熔断开启
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //请求数达到后才计算
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //休眠时间窗
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") //设置断路器打开的错误率，单位%
//    })
    @HystrixCommand //不加注解，服务降级不会生效
    @GetMapping("/getProductInfoList")
    public String getProductInfoList() {
//        if (number % 2 == 0) {
//            return "success";
//        }
        RestTemplate restTemplate = new RestTemplate();
        /**
         * 参数1：请求的url
         * 参数2：请求的入参，传递的是List<String > productIdList
         * 参数3：返回的类型。http请求实际上传递的是字符，只不过feign用对象来接收的时候再转换一次
         */
        return restTemplate.postForObject("http://localhost:8001/product/listForOrder",
                Arrays.asList("157875227953464068"),
                String.class);
    }

    /**
     * 降级逻辑的实现
     * @return
     */
    private String fallback() {
        return "太拥挤了，请稍后再试吧~";
    }

    /**
     * 降级逻辑的默认实现
     * @return
     */
    private String defaultFallback() {
        return "默认降级：太拥挤了，请稍后再试吧~";
    }
}
